#include "total.h" //struct: numStack, signStack, 
// functions: initNumStack, initSignStack, pushSign, popSign, stackEmpty, checkExpression

int isOperator(char c);

int checkExpression(char *expression) {
    signStack sg;
    int len;
    char e;
    
    initSignStack(&sg);
    len = strlrn(expression);

    //第一类不合法：括号无法匹配
    for (int i = 0; i < len; i++) {
        if (expression[i] == '(') 
            pushSign(&sg, '(');
        if (expression[i] == ')') {
            if (stackEmpty(&sg)) {
                return 0;
            }
            popSign(&sg, &e);
        }
    }
    if (!stackEmpty(&sg)) {
        return 0;
    }

    //第二类不合法：操作符左右元素不合法
    for (int i = 0; i < len; i++) {
        if (expression[i] == '-') {
            if (i == 0 || expression[i-1] == '(') {
                i++;
            }
        }
        if (isOperator(expression[i])) {
            if (i == 0 || isOperator(expression[i-1]) || isOperator(expression[i+1])) {
                return 0;
            }
        }
    }

    //第三种不合法：左右括号相邻
    for (int i = 0; i < len; i++) {
        if (expression[i] == '(' && expression[i+1] == ')') {
            return 0;
        }
        if (expression[i] == ')' && expression[i+1] == '(') {
            return 0;
        }
    }
}

void initNumStack (numStack *s) {
    s->top = -1;

    return 0;
}

void initSignStack (signStack *s) {
    s->top = -1;

    return 0;
}

int stackEmpty (numStack *s) {
    return (s->top == -1);
}

void pushSign (signStack *s, char c) {
    if (s->top == MAX-1) {
        printf("Error: signStack is full\n");
        exit(1);
    }

    s->top++;
    s->data[s->top] = c;

    return 0;
}

void popSign (signStack *s, char *e) {
    if (s->top == -1) {
        printf("Error: signStack is empty\n");
        exit(1);
    }
    *e = s->data[s->top];
    s->top--;

    return 0;
}

int isOperator(char c) {
    if (c == '+' || c == '-' || c == '*' || c == '/' || c == '^') {
        return 1;
    } 
    else 
        return 0;
}